package com.handong.handserialprogram.module.createmission.searchring;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.utils.ViewUtil;

import java.util.List;

/**
 * Created by userKey on 2017/8/2.
 */

public class SearchRingAdapter extends RecyclerView.Adapter<SearchRingAdapter.ViewHolder> {

    private static final int NORMAL_TEXT = Color.parseColor("#6198FE");
    private List<FootRingNewEntity> mFootRingList;
    private SearchRingFragment mFragment;
    private RecyclerView mRecyclerView;
    private MaterialDialog mRouteDialog;
    private List<PersonEntity> mPersonEntityList;

    public SearchRingAdapter(List<PersonEntity> personEntityList,List<FootRingNewEntity> footRingList, SearchRingFragment fragment) {
        mFootRingList = footRingList;
        mFragment = fragment;
        mPersonEntityList=personEntityList;
    }

    public void SetRingList(List<FootRingNewEntity> footRingList)
    {
        mFootRingList=footRingList;
    }

    @Override
    public SearchRingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mRecyclerView= (RecyclerView) parent;

        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapter_ring_list_item, parent, false);
        return new SearchRingAdapter.ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final SearchRingAdapter.ViewHolder holder,final int position) {
        FootRingNewEntity entity = mFootRingList.get(position);
        holder.mHolderEntity = entity;
        holder.ringID.setText(entity.getRingID());
        holder.ringActualDistance.setText(entity.getActualRingDistance() + "m");
        holder.ringSetDistance.setText(entity.getSetRingDistance() + "m");
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            holder.ringActualDistance.setTextColor(ColorContant.PERSON_ESCAPE);
        } else {
            holder.ringActualDistance.setTextColor(NORMAL_TEXT);
        }
        if(entity.isResult()) {
            if (entity.isAudioError() || entity.isSimError() || entity.isUwbError() || entity.isWifiError() || entity.isIs4gError()) {
                holder.equipmentStatus.setEnabled(false);
                holder.mCriminalName.setVisibility(View.GONE);
                holder.ringStatus.setVisibility(View.VISIBLE);
                setBtnState(holder, R.drawable.icon_ring_sleep, "自检异常", Color.parseColor("#FF0000"), true);
            } else {
                holder.equipmentStatus.setEnabled(true);
                setBtnState(holder, R.drawable.icon_ring_working, "选择犯人", ColorContant.PERSON_NORMAL, true);
                if (entity.isMyBingding()) {

                    holder.equipmentStatus.setChecked(true);
                    if (entity.getCriminalName().equals("")) {
                        holder.mCriminalName.setVisibility(View.GONE);
                        if(holder.isAllPersonBinded()==0) {
                            holder.ringStatus.setVisibility(View.GONE);
                        }
                        else{
                            holder.ringStatus.setVisibility(View.VISIBLE);
                        }
                    } else {
                        holder.mCriminalName.setVisibility(View.VISIBLE);
                        holder.mCriminalName.setText(entity.getCriminalName());
                        holder.ringStatus.setVisibility(View.GONE);
                    }
                } else {
                    holder.ringStatus.setVisibility(View.VISIBLE);
                    setBtnState(holder, R.drawable.icon_ring_sleep, "自检成功", ColorContant.PERSON_NORMAL, true);
                    holder.equipmentStatus.setChecked(false);
                    holder.mCriminalName.setVisibility(View.GONE);
                    //holder.ringStatus.setVisibility(View.GONE);
                    if (!entity.getCriminalId().equals("")) {
                        //mPersonEntityList.add(new PersonEntity(entity.getCriminalName(), entity.getCriminalId()));
                        for (PersonEntity personEntity:mPersonEntityList)
                        {
                            if (entity.getCriminalId().equals(personEntity.getId()))
                            {
                                personEntity.setSelected(false);
                            }

                        }
                    }
                    entity.setCriminalId("");
                    entity.setCriminalName("");


                }
            }
        }
        else{
            holder.equipmentStatus.setEnabled(false);
            entity.setBingding(false);
            entity.setCriminalId("");
            entity.setCriminalName("");
            holder.equipmentStatus.setChecked(false);
            holder.mCriminalName.setVisibility(View.GONE);
            holder.ringStatus.setVisibility(View.VISIBLE);
            setBtnState(holder, R.drawable.icon_ring_sleep, "自检中" ,Color.parseColor("#C0C0C0"), false);
            //setBtnState(holder, R.drawable.icon_ring_sleep, "自检中", Color.parseColor("#FF0000"), true);
        }



        //int currentPosition=position;






//        if(entity.isBingding()){
//            //已绑定
//            if(!entity.isMyBingding()){
//                setBtnState(holder,R.drawable.icon_ring_sleep,"已绑",Color.parseColor("#C0C0C0"),false);
//            }else if(entity.isMyBingding()&&(entity.getStatus()!=FootRingStatus.NORMAL)){
//                setBtnState(holder,R.drawable.icon_ring_sleep,"",Color.parseColor("#C0C0C0"),false);
//            }else if(entity.isMyBingding()){
//                if (entity.isNormalWork()) {
//                    setBtnState(holder,R.drawable.icon_ring_working,"休眠",ColorContant.RING_CANCEL_BTN,true);
//                } else {
//                    setBtnState(holder,R.drawable.icon_ring_sleep,"激活",ColorContant.MISSION_NORMAL,true);
//                }
//            }
//        }else{
//            //未绑定
//            if(entity.getStatus()!=FootRingStatus.NORMAL){
//                setBtnState(holder,R.drawable.icon_ring_sleep,"",Color.parseColor("#C0C0C0"),false);
//            } else if (entity.isNormalWork()) {
//                setBtnState(holder,R.drawable.icon_ring_working,"休眠",ColorContant.RING_CANCEL_BTN,true);
//            } else {
//
//                // todo 改为一对一
////                boolean tag=false;
////                for (FootRingNewEntity footRingEntity:mFootRingList) {
////                    if(footRingEntity.isMyBingding()){
////                        tag=true;
////                    }
////                }
////                if(tag){
////                    setBtnState(holder,R.drawable.icon_ring_sleep,"激活",Color.parseColor("#C0C0C0"),false);
////                }else
////                setBtnState(holder,R.drawable.icon_ring_sleep,"激活",ColorContant.MISSION_NORMAL,true);
//                // todo 一对多
//                setBtnState(holder,R.drawable.icon_ring_sleep,"激活",ColorContant.MISSION_NORMAL,true);
//            }
//        }

    }

    private void setBtnState(SearchRingAdapter.ViewHolder holder,int iconID,String des,int color,boolean isEnabled){
        GradientDrawable drawable = (GradientDrawable) holder.ringStatus.getBackground();
        holder.ringIcon.setImageResource(iconID);
        if(!TextUtils.isEmpty(des))
        holder.ringStatus.setText(des);
        drawable.setColor(color);
        holder.mActivateLayout.setEnabled(isEnabled);
    }







    public View getView(int posstion) {
        ViewHolder holder= (ViewHolder) mRecyclerView.findViewHolderForLayoutPosition(posstion);
        return  holder.ringStatus;
    }

    @Override
    public int getItemCount() {
        return mFootRingList == null ? 0 : mFootRingList.size();
    }

    protected void destroy(){
        mFragment = null;
    }

    public class ViewHolder extends RecyclerView.ViewHolder  {

        private FootRingNewEntity mHolderEntity;

        private TextView ringID, ringSetDistance, ringActualDistance, ringStatus,mCriminalName;
        private FrameLayout mActivateLayout;
        private ImageView ringIcon;
        private AppCompatCheckBox equipmentStatus;
        //private int position=0;
        //private boolean isChecked;

        public ViewHolder(View itemView) {
            super(itemView);

            ringIcon = (ImageView) itemView.findViewById(R.id.ringItemIcon);
            ringID = (TextView) itemView.findViewById(R.id.ringItemID);
            ringSetDistance = (TextView) itemView.findViewById(R.id.ringItemSetDistance);
            ringActualDistance = (TextView) itemView.findViewById(R.id.ringItemActualDistance);
            ringStatus = (TextView) itemView.findViewById(R.id.ringItemBtnSet);
            mCriminalName=(TextView) itemView.findViewById(R.id.crimanalName);
            mActivateLayout = (FrameLayout) ringStatus.getParent();
            //mActivateLayout.setOnClickListener(this);
            equipmentStatus=(AppCompatCheckBox)itemView.findViewById(R.id.choosePersonStatus);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mHolderEntity.isWifiError()||mHolderEntity.isUwbError()||mHolderEntity.isSimError()||mHolderEntity.isAudioError()||mHolderEntity.isIs4gError())
                    {

                    }
                    else {
                        if (equipmentStatus.isEnabled()) {
                            if (!mHolderEntity.isMyBingding()) {
                                //mHolderEntity.setIsCheck(true);
                                mHolderEntity.setMyBingding(true);

                            } else {
                                //mHolderEntity.setChecked(false);
                                mHolderEntity.setMyBingding(false);

                            }
                            notifyDataSetChanged();
                        }
                    }
                }
            });
            ringStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //getRouteSuccess(position);
                    if(mHolderEntity.isResult()) {
                        if (mHolderEntity.isWifiError() || mHolderEntity.isUwbError() || mHolderEntity.isSimError() || mHolderEntity.isAudioError() || mHolderEntity.isIs4gError()||!mHolderEntity.isMyBingding()) {
                            showCheckDialog(mHolderEntity.getRingID(), "\r\nWIFI模块:" + (mHolderEntity.isWifiError() ? "异常" : "正常") + "\r\n测距模块:" + (mHolderEntity.isUwbError() ? "异常" : "正常") + "\r\nSIM卡模块:" + (mHolderEntity.isSimError() ? "异常" : "正常") + "\r\n声音模块:" + (mHolderEntity.isAudioError() ? "异常" : "正常") + "\r\n4G模块:" + (mHolderEntity.isIs4gError() ? "异常" : "正常"));
                        } else {
                            getRouteSuccess();
                        }
                    }

                }
            });

        }

        /**
         * 判断当前是否所有犯人都已经被绑定
         * @return
         */
        public int isAllPersonBinded(){
            int bindedPersonCount=0;
            for (PersonEntity entity:mPersonEntityList)
            {
                if (!entity.isSelected())
                {
                    bindedPersonCount++;
                }
            }
            return bindedPersonCount;

        }

        /**
         * 脚环自检结果
         */
        public void showCheckDialog(final String paramString,final String errorString) {
            ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(mFragment.getContext())
                    .content("脚环"+paramString+"自检完成，详情："+errorString)
                    .negativeColorRes(R.color.dialog_bg)
                    .negativeText(R.string.dialog_negative_text)
                    .build());
        }

        /**
         * 录入线路成功
         */
        public void getRouteSuccess() {
            int len =mPersonEntityList .size();
            int notSelectedPersonCount=isAllPersonBinded();
            String[] itemName = new String[notSelectedPersonCount];
            String[] itemCode = new String[notSelectedPersonCount];
            int j=0;
            int checked = -1;
            String code = mHolderEntity.getCriminalId();
            PersonEntity entity = null;
            for (int i = 0; i < len; i++) {
                entity = mPersonEntityList.get(i);
                if (!entity.isSelected())
                {
                    itemName[j] = entity.getName();
                    itemCode[j] = entity.getId();
                    j++;
                }
                else{
                    if (!TextUtils.isEmpty(code) && entity.getId().equals(code)) {
                        checked = i;
                    }
                }
            }

            if (mRouteDialog!=null)
            {
                mRouteDialog.dismiss();
            }

            mFragment.dismissLoadingDialog();
            showRouteDialog(itemName, itemCode, checked);
        }

        /**
         * 选择线路
         */
        private void showRouteDialog(String[] nameArr, final String[] codeArr, int checked) {

            //if (mRouteDialog == null) {
                mRouteDialog = new MaterialDialog.Builder(mFragment.getContext())
                        .title("选择犯人")
                        .items(nameArr)
                        .canceledOnTouchOutside(false)
                        .widgetColorRes(R.color.colorPrimary)
                        .itemsCallbackSingleChoice(checked, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                if (-1 == which) {
                                    return true;
                                }
                                mHolderEntity.setCriminalId(codeArr[which]);
                                mHolderEntity.setCriminalName(text.toString());
                                for(PersonEntity personEntity :mPersonEntityList)
                                {
                                    if (personEntity.getId().equals(codeArr[which]))
                                    {
                                        personEntity.setSelected(true);
                                    }
                                }
                                //mPersonEntityList.remove(which);
                                notifyDataSetChanged();
                                return true;
                            }
                        })
                        .positiveColorRes(R.color.back_ground_green)
                        .positiveText(R.string.dialog_positive_text)
                        .negativeColorRes(R.color.bg_gray)
                        .negativeText(R.string.dialog_negative_text)
                        .neutralColorRes(R.color.login_warning_bg_color)

                        .build();
            //}
            ViewUtil.removeHomeKeyListener(mRouteDialog);
        }

    }

}
